package future;

import java.util.concurrent.*;

/**
 * @author fei
 * @date 2023/1/3 19:32
 * @description FutureTask以及线程池使用
 */
public class FutureThreadPoolDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        m1();
        System.out.println("--------------------------------");

        // 3个任务，目前开启多个异步任务线程来处理，请问耗时多少
        long startTime = System.currentTimeMillis();

        // 线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        FutureTask<String> futureTask1 = new FutureTask<>(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "task1 over";
        });
        threadPool.submit(futureTask1);

        FutureTask<String> futureTask2 = new FutureTask<>(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "task2 over";
        });
        threadPool.submit(futureTask2);

        System.out.println(futureTask1.get());
        System.out.println(futureTask2.get());

        try{ TimeUnit.MILLISECONDS.sleep(300);} catch (InterruptedException e) { e.printStackTrace(); }

        long endTime = System.currentTimeMillis();
        System.out.println("----costTime: " + (endTime - startTime) + " 毫秒");
        System.out.println(Thread.currentThread().getName() + "\t ------end");

        threadPool.shutdown();
    }

    /**
     * 3个任务，目前只有一个线程 main 来处理，请问耗时多少
     */
    private static void m1() {
        long startTime = System.currentTimeMillis();
        try{ TimeUnit.MILLISECONDS.sleep(500);} catch (InterruptedException e) { e.printStackTrace(); }
        try{ TimeUnit.MILLISECONDS.sleep(300);} catch (InterruptedException e) { e.printStackTrace(); }
        try{ TimeUnit.MILLISECONDS.sleep(300);} catch (InterruptedException e) { e.printStackTrace(); }
        long endTime = System.currentTimeMillis();
        System.out.println("----costTime: " + (endTime - startTime) + " 毫秒");
        System.out.println(Thread.currentThread().getName() + "\t ------end");
    }

}
